package com.melody.rest.util;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.melody.rest.domain.RestData;
import com.melody.rest.domain.RestSysUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public LoginInterceptor(RedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //设置编码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

        //1、判断是否携带token
        String token = request.getHeader("authorization");
        System.out.println(token);
        if(token==null || "".equals(token)){
            RestData restData = RestData.builder().code("401").msg("你未登录").build();
            String jsonRestData = JSONObject.toJSONString(restData);
            response.setStatus(401);
            response.getWriter().write(jsonRestData);
            return false;
        }
        Map<String, Object> userMap=redisTemplate.opsForHash().entries(token);
        RestSysUser restSysUser = BeanUtil.fillBeanWithMap(userMap, new RestSysUser(), false);
        //2、判断redis里面是否存在token
        if(userMap.isEmpty()){
            RestData restData = RestData.builder().code("401").msg("你未登录").build();
            String jsonRestData = JSONObject.toJSONString(restData);
            response.setStatus(401);
            response.getWriter().write(jsonRestData);
            return false;
        }

        //3、判断账号情况
        if(restSysUser.getUsername()!=null){
            //获取数据库账号情况
            //比对，如果账号异常，则不能访问
            //return false;
        }
        return true;
    }
}
